/*
 * Copyright (c) 2025 李伟国
 * SQL-API is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
 * KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
 * NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package com.moyu.sql.business.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.function.support.RouterFunctionMapping;

@Component
public class RouterRefreshListener implements ApplicationContextAware {
    protected ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@Nullable ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @EventListener(ContextRefreshedEvent.class)
    public void onApplicationEvent(@SuppressWarnings("unused") ContextRefreshedEvent event) {
        // 延迟获取routerFunctionMapping，避免循环依赖
        RouterFunctionMapping routerFunctionMapping = applicationContext.getBean(RouterFunctionMapping.class);
        DynamicRouterConfig dynamicRouterConfig = applicationContext.getBean(DynamicRouterConfig.class);

        // 初始路由设置
        routerFunctionMapping.setRouterFunction(dynamicRouterConfig.getCurrentRouter());
    }

    @EventListener
    public void onRouterRefreshed(@SuppressWarnings("unused") RouterRefreshedEvent event) {
        RouterFunctionMapping routerFunctionMapping = applicationContext.getBean(RouterFunctionMapping.class);
        DynamicRouterConfig dynamicRouterConfig = applicationContext.getBean(DynamicRouterConfig.class);

        routerFunctionMapping.setRouterFunction(dynamicRouterConfig.getCurrentRouter());
    }
}
